<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="1200px" append-to-body custom-class="import-dialog"
               @close="close"
    >
      <el-form :model="form" :rules="rules" ref="form" label-position="left" label-width="140px" class="add-form">
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="合同模板" prop="contractTemplateId">
              <el-select v-model="form.contractTemplateId" placeholder="请选择" @change="selectContractTemplate"
                         filterable
              >
                <el-option :label="item.label" :value="item.value" v-for="item in contractTemplateList"
                           :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最晚签约日期" prop="latestSigningTime">
              <el-date-picker
                v-model="form.latestSigningTime"
                value-format="yyyy-MM-dd"
                align="right"
                type="date"
                placeholder="请选择最晚签约日期"
                style="margin-right: 10px;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSubmit" v-text="loading ? '提交中...' : '确 定'">确
          定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { houseManagerList } from '@/api/contract/proprietor'
import {
  pageElectronicVisa,
} from '@/api/contract/lessee'

import { debounce } from '@/utils'
import { compareDate, isBetween, isOverlap } from '@/utils/common/moment'
import { addDeliveryOrder, reissueContract } from '@/api/contract/deliveryOrder'

export default {
  name: 'add',
  dicts: ['contract_type'],
  components: {
  },
  props: {
    title: {
      default: '新增设施清单'
    },
    value: {
      default: false
    },
    formData: {},
    isRelaunch: {
      type: Boolean,
      default: false
    },
    // 合同类型 合同类型 1.业主合同 2.租客合同
    contractType: {
      type:String,
      default:''
    }
  },
  data() {
    return {
      // visible: false,
      loading: false,
      //房管家列表
      houseManagerList: [],
      // 合同模板列表
      contractTemplateList: [],
      // 生成账单弹窗
      dialogGenerateBillVisible: false,
      // 房屋甲方人类型
      houseMemberType: '',//
      form: {
        deliveryOrderId: "", //交割单id
        deliveryOrderType: "", //交割单类型：1.交房；2.租房
        relatedContractId: "", //关联合同id
        latestSigningTime: "", //最晚签约时间
        contractTemplateId: "", //合同模板id
        contractTemplateName: "" //模板名称
      },
      // 租期列表
      rentalTimeList: [],
      latestPaymentDatePickerOption: {
        disabledDate(time) {
          return compareDate(time, new Date(), '<')
          // return time.getTime() < Date.now()
        }
      },
      templateType: '',
      rules: {
        contractTemplateId: [
          { required: true, message: '请选择合同模板', trigger: 'change' }
        ],
        latestSigningTime: [
          { required: true, message: '请选择最晚签约日期', trigger: 'change' }
        ],
      },
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true,
      deep: true
    },
  },
  methods: {
    init() {
      //重置
      this.reset()
      //获取房管家列表
      this.getHouseManagerList()
      // 获取电子合同模板列表
      this.getElectronicVisaList()

    },
    //重置表单
    reset() {
      this.form = {
        deliveryOrderType: this.formData['deliveryOrderType'], //交割单类型：1.交房；2.租房
        relatedContractId: this.formData['relatedContractId'], //关联合同id
        latestSigningTime: "", //最晚签约时间
        contractTemplateId: "", //合同模板id
        contractTemplateName: "" //模板名称
      }
      //是否重新发起合同
      if (this.isRelaunch) {
        this.form = {
          deliveryOrderId:this.formData.deliveryOrderId,
          deliveryOrderType: this.formData.deliveryOrderType,
          relatedContractId: this.formData.relatedContractId,
          latestSigningTime: this.formData.latestSigningTime,
          contractTemplateId: this.formData.contractTemplateId,
          contractTemplateName: this.formData.contractTemplateName,
        }
      }
      console.log('form', this.form)
      this.resetForm('form')
    },
    //获取房管家列表
    getHouseManagerList() {
      let params = {
        roleKey: 'houseKeeper'
      }
      houseManagerList(params).then(response => {
        this.houseManagerList = response.data.map(item => {
          return {
            label: item.userName,
            value: item.userId
          }
        })
      })
    },
    //获取电子合同模板列表
    getElectronicVisaList() {
      console.log('formData', this.formData, this.formData.deliveryOrderType, this.formData.signingMode)
      let templateName = ''
      if(this.formData.signingMode === '3' || this.contractType === '1' || this.formData.deliveryOrderType === '1'){
        templateName = '设施清单_房东'
      }else if (this.contractType === '2' || this.formData.deliveryOrderType === '2'){
        if(this.formData.signingMode === '1'){
          templateName = '设施清单_房东'
        }else if(this.formData.signingMode === '2'){
          templateName = '设施清单_租客'
        }
      }
      let params = {
        templateName: templateName
      }
      console.log('params', params)
      pageElectronicVisa(params).then(response => {
        if (!response.data.signTemplates) {
          this.contractTemplateList = []
          return
        }
        this.contractTemplateList = response.data.signTemplates.map(item => {
          return {
            label: item.signTemplateName,
            value: item.signTemplateId
          }
        })
      })
    },
    // 选择合同模板回调
    selectContractTemplate(val) {
      let template = this.contractTemplateList.find(item => item.value == val)
      if (template) {
        this.form.contractTemplateName = template.label
      }
    },
    // 处理提交表单
    handleSubmit:debounce(function(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          let api;
          if (this.isRelaunch) {
            api = reissueContract
          }else{
            api = addDeliveryOrder
          }
          this.loading = true
          api(this.form).then(res => {
            this.$message.success(res.msg|| '操作成功')
            this.$emit('success')
            this.visible = false
            this.loading = false
          }).catch(err => {
            console.log('err', err)
            this.loading = false
          })
        }
      })

    }, 300, true),
    //关闭
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;

  .dialog-footer {
    text-align: center;
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

</style>

